/**
 * @Project : ProgrammingExercises
 * @Package : ForOffer
 * @File : Q018.java
 * @Author : WangRuoyu
 * @Date 2022/12/27 11:08
 */

package foroffers;

import util.ListNode;

public class Q0018 {
    public ListNode deleteNode(ListNode head, int val) {
        if (head == null) {
            return head;
        } else if (head.val == val) {
            head = head.next;
            return head;
        }
        ListNode s = head;
        ListNode p = head;

        while (p.next != null) {
            if (p.next.val == val) {
                p.next = p.next.next;
                return s;
            }
            p = p.next;
        }

        return s;
    }

    public static void main(String[] args) {
        Q0018 sl = new Q0018();
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        int val = 5;
        ListNode p = sl.deleteNode(head, val);
        while (p != null) {
            System.out.println(p.val);
            p = p.next;
        }
    }
}
